package org.JWCB.job.handler;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.JWCB.common.core.constants.CacheConstants;
import org.JWCB.common.redis.service.RedisService;
import org.JWCB.job.constant.QuestionConstants;
import org.JWCB.job.domain.question.Question;
import org.JWCB.job.domain.question.vo.HotQuestionListVo;
import org.JWCB.job.mapper.question.QuestionMapper;
import org.JWCB.job.mapper.user.UserSubmitMapper;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@RequiredArgsConstructor
public class QuestionXxlJobHandler {

    private final RedisService redisService;
    private final UserSubmitMapper userSubmitMapper;
    private final QuestionMapper questionMapper;

    @XxlJob("hotQuestionJobHandler")
    public void hotQuestionJobHandler() {
        log.info("开始执行热门题目定时任务");
        try {
            // 1. 查询提交次数最多的题目ID
            List<Long> hotQuestionIds = userSubmitMapper.selectHotQuestionIds(QuestionConstants.HOT_QUESTION_COUNT);
            if (hotQuestionIds.isEmpty()) {
                // 如果没有热门题目，设置空值标记
                redisService.setCacheObject(CacheConstants.HOT_QUESTION_EMPTY_KEY, "",
                        CacheConstants.HOT_QUESTION_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
                log.info("没有找到热门题目，已设置空值标记");
                return;
            }

            // 2. 查询题目详情
            List<Question> questions = questionMapper.selectBatchIds(hotQuestionIds);
            if (questions.isEmpty()) {
                // 如果题目不存在，设置空值标记
                redisService.setCacheObject(CacheConstants.HOT_QUESTION_EMPTY_KEY, "",
                        CacheConstants.HOT_QUESTION_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
                log.info("热门题目不存在，已设置空值标记");
                return;
            }

            // 3. 转换为VO对象
            List<HotQuestionListVo> hotQuestionList = questions.stream()
                    .map(question -> {
                        HotQuestionListVo vo = new HotQuestionListVo();
                        vo.setQuestionId(question.getQuestionId());
                        vo.setTitle(question.getTitle());
                        vo.setDifficulty(question.getDifficulty());
                        // 获取该题目的提交次数
                        Integer submitCount = userSubmitMapper.selectSubmitCountByQuestionId(question.getQuestionId());
                        vo.setSubmitCount(submitCount != null ? submitCount : 0);
                        return vo;
                    })
                    .collect(Collectors.toList());

            // 4. 删除旧缓存
            redisService.deleteObject(CacheConstants.HOT_QUESTION_LIST_KEY);
            redisService.deleteObject(CacheConstants.HOT_QUESTION_EMPTY_KEY);

            // 5. 写入新缓存
            redisService.setCacheObject(CacheConstants.HOT_QUESTION_LIST_KEY, hotQuestionList,
                    CacheConstants.HOT_QUESTION_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
            log.info("热门题目缓存更新成功，共{}条数据", hotQuestionList.size());
        } catch (Exception e) {
            log.error("热门题目定时任务执行失败", e);
            XxlJobHelper.handleFail("热门题目定时任务执行失败：" + e.getMessage());
        }
    }
}
